package com.yexiao.cofe.util;

import com.yexiao.cofe.business.mapper.PermissionMapper;
import com.yexiao.cofe.business.mapper.RoleMapper;
import com.yexiao.cofe.business.mapper.UserMapper;
import com.yexiao.cofe.business.pojo.Permission;
import com.yexiao.cofe.business.pojo.Role;
import com.yexiao.cofe.business.pojo.User;
import com.yexiao.cofe.common.exception.BusinessException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

public class SystemUtil {

    public static UserMapper userMapper = SpringContextUtil.getBean(UserMapper.class);
    public static PermissionMapper permissionMapper = SpringContextUtil.getBean(PermissionMapper.class);
    public static RoleMapper roleMapper = SpringContextUtil.getBean(RoleMapper.class);

    public static User getUser(String token) {
        String userId = getUserId(token);
        User user = userMapper.selectByUID(userId);
        if(user == null) {
            throw new BusinessException("用户不存在");
        }

        return user;
    }

    public static String getUserId(String token) {
        return JwtUtil.getUserId(token);
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static <T> void checkErrorIfNull(T obj, String errorMsg) {
        if(obj == null) {
            throw new BusinessException(errorMsg);
        }
    }

    public static <T> void checkErrorIfNotNull(T obj, String errorMsg) {
        if(obj != null) {
            throw new BusinessException(errorMsg);
        }
    }

    public static List<String> listUserPermission(String token) {
        String userId = getUserId(token);
        List<Role> roleList = roleMapper.listUserRole(userId);
        Set<Integer> roleIdSet = roleList.stream().map(Role::getId).collect(Collectors.toSet());
        List<Permission> permission = permissionMapper.listPermission(new ArrayList<>(roleIdSet));
        Set<String> permissionIdSet = permission.stream().map(Permission::getPermissionId).collect(Collectors.toSet());
        return new ArrayList<>(permissionIdSet);
    }
}
